package com.bonc.excel.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.bonc.excel.biz.ExcelService;
import com.bonc.excel.dto.request.RequestDto;
import com.bonc.excel.utils.EasyExcelUtis;
import com.spire.xls.*;
import com.spire.xls.Worksheet;
import com.spire.xls.collections.WorksheetsCollection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@Slf4j
@RequestMapping("/")
@CrossOrigin
public class PoiController {

    //private static final ClassPool parent = ClassPool.getDefault();
    


    @Autowired
    ExcelService excelService;


    @RequestMapping(value = "downloadExcel", method = RequestMethod.GET)
    //public void download(@RequestParam(name = "code", required = false) String code, HttpServletResponse response) throws Exception {
    public void download(/*@RequestBody(required = false )*/RequestDto paramDto, HttpServletResponse response) throws Exception {
        log.info("数据运营资产周报报表下载 start");
        String nowDate = DateUtil.format(LocalDateTime.now(), "yyyyMMdd");
        String fileName = "数据运营资产周报_".concat(nowDate);
        EasyExcelUtis.setResponse(response,fileName);
        Map<String, List> data = excelService.getData(paramDto);

        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(response.getOutputStream())
                    .registerWriteHandler(EasyExcelUtis.styleWrite()).build();
            AtomicInteger sheetIndex = new AtomicInteger(0);
            ExcelWriter finalExcelWriter = excelWriter;
            data.forEach((name, datas)->{
                WriteSheet sheet = EasyExcel.writerSheet(sheetIndex.get(), name).head(datas.get(0).getClass()).build();
                finalExcelWriter.write(datas, sheet);
                sheetIndex.getAndIncrement();
            });
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    @RequestMapping(value = "downloadImage", method = RequestMethod.GET)
    public void downloadImage(@RequestParam(name = "code", required = false) String code,HttpServletResponse response) throws Exception {
        log.info("downloadImage start");
      //  EasyExcelUtis.setResponse(response,fileName);
        Map<String, List> data = excelService.getData(null);
        data.forEach((name, datas)->{
         /*   ServletOutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }*/
            OutputStream outputStream = new ByteArrayOutputStream();
            EasyExcel.write(outputStream);
            InputStream inputStream = new ByteArrayInputStream(((ByteArrayOutputStream) outputStream).toByteArray());
           /* try {
                outputStream.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }*/
            genImage(inputStream);
        });

      /*  String nowDate = DateUtil.format(LocalDateTime.now(), "yyyyMMdd");
        String fileName = "数据运营资产周报_".concat(nowDate);

        String filePath = "C:\\Users\\EDY\\Downloads\\数据运营资产周报_20240914 (2).xlsx";

        //加载Excel工作表
        Workbook wb = new Workbook();
        wb.loadFromFile(filePath);

        WorksheetsCollection worksheets = wb.getWorksheets();
        String imagePath = "C:\\Users\\EDY\\Desktop\\img\\%s";
        for (int i = 0; i < worksheets.size(); i++) {
            Worksheet sheet = wb.getWorksheets().get(i);
            //调用方法将Excel工作表保存为图片
            sheet.saveToImage(String.format(imagePath, RandomUtil.randomString(3).concat("png")));
        }*/



    }

    public String genImage(InputStream inputStream){
        Workbook wb = new Workbook();
        //wb.loadFromFile(filePath);
        wb.loadFromStream(inputStream);

        WorksheetsCollection worksheets = wb.getWorksheets();
        String imagePath = "C:\\Users\\EDY\\Desktop\\img\\%s";
        for (int i = 0; i < worksheets.size(); i++) {
            Worksheet sheet = wb.getWorksheets().get(i);
            //调用方法将Excel工作表保存为图片
            sheet.saveToImage(String.format(imagePath, RandomUtil.randomString(3).concat(".png")));
        }
        return "";
    }

    public static void main(String[] args) {
        String filePath = "C:\\Users\\EDY\\Downloads\\数据运营资产周报_20240914 (2).xlsx";
        //加载Excel工作表
        Workbook wb = new Workbook();
        wb.loadFromFile(filePath);
        WorksheetsCollection worksheets = wb.getWorksheets();
        String imagePath = "C:\\Users\\EDY\\Desktop\\img\\%s";
        for (int i = 0; i < worksheets.size(); i++) {
            Worksheet sheet = wb.getWorksheets().get(i);
            //调用方法将Excel工作表保存为图片

            sheet.saveToImage(String.format(imagePath, RandomUtil.randomString(3).concat(".png")));
        }
        System.out.println("成功");
    }


}